﻿using MediatR;
using Medical.Api.Read.Application.Command.DepartmentManagement.Adopted;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System.Linq;

namespace Medical.Api.Read.Application.Handler.DepartmentManagement.Adopted
{
    /// <summary>
    /// 领用申请查询处理器
    /// </summary>
    public class GetAdoptedCommandHandler : IRequestHandler<GetAdoptedCommands, ApiResult<List<TouseTable>>>
    {
        private readonly ILogger<GetAdoptedCommandHandler> logger;
        private readonly IBaseRepository<TouseTable> touseRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="touseRep">领用表仓储接口</param>
        public GetAdoptedCommandHandler(ILogger<GetAdoptedCommandHandler> logger, IBaseRepository<TouseTable> touseRep)
        {
            this.logger = logger;
            this.touseRep = touseRep;
        }

        /// <summary>
        /// 处理领用申请查询请求
        /// </summary>
        /// <param name="request">查询请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>领用表列表结果</returns>
        public async Task<ApiResult<List<TouseTable>>> Handle(GetAdoptedCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"开始查询领用申请列表，申请时间：{request.ApplicationTime}，领用状态：{request.TouseStatus}");
                
                // 获取未删除的所有记录
                var query = touseRep.GetAll().Where(x => !x.IsDeleted);
                
                // 时间查询条件：如果提供了申请时间，则按申请时间筛选
                // 查询当天的记录（从当天0点到23:59:59）
                if (request.ApplicationTime.HasValue)
                {
                    DateTime startDate = request.ApplicationTime.Value.Date;
                    DateTime endDate = startDate.AddDays(1).AddSeconds(-1);
                    
                    query = query.Where(x => x.ApplicationTime >= startDate && x.ApplicationTime <= endDate);
                    
                    logger.LogInformation($"按申请时间筛选：{startDate} 至 {endDate}");
                }
                //领用状态的查询
                if (request.TouseStatus > 0)
                {
                    query = query.Where(x=>x.TouseStatus==request.TouseStatus);
                    logger.LogInformation($"按领用状态筛选：{request.TouseStatus}");
                }
                var result = query.ToList();
                
                logger.LogInformation($"领用申请列表查询成功，返回 {result.Count} 条记录");

                return new ApiResult<List<TouseTable>>
                {
                    Code = ApiEnums.Success,
                    Data = result,
                    Msg = "领用申请列表显示成功!"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询领用申请列表时发生异常：{ex.Message}");
                
                return new ApiResult<List<TouseTable>>
                {
                    Code = ApiEnums.Error,
                    Data = new List<TouseTable>(),
                    Msg = $"查询领用申请列表失败：{ex.Message}"
                };
            }
        }
    }
}
